
package com.scalar.chiptrack.operations.lotshipping.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.engineering.dao.EngineeringDAO;
import com.scalar.chiptrack.operations.LotView;
import com.scalar.chiptrack.operations.lotshipping.dao.LotShippingDAO;
import com.scalar.chiptrack.operations.lotshipping.forms.LotShippingForm;
import com.scalar.chiptrack.operations.process.ProcessStep;
import com.scalar.chiptrack.operations.process.dao.ProductDao;



public final class LotShippingAction extends ChipTrackAction {

    public ActionForward execute (ActionMapping mapping,
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response)
                              throws Exception {

        String retval = "failure";
        HashMap errors = new HashMap();
        HttpSession session = request.getSession();
        String action = request.getParameter ("action");
        LotShippingForm lotShippingForm = (LotShippingForm) form;


        if ("loadProcessSteps".equalsIgnoreCase (action)) {
            try {
                int productId = lotShippingForm.getProductId();
                ArrayList processStepList = ProductDao.getProcessStepInfoByProductId (productId);
                session.setAttribute ("processStepList", processStepList);

                retval = "success";
            }
            catch (ScalarException se) {
                // Exception while interaction with database
                errors.put ("Could not load Process step information", "Internal Server Error");
                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
            }
        }


        if ("loadLots".equalsIgnoreCase (action)) {
            try {
                String processStep = lotShippingForm.getProcessStep();

                if ((processStep != null) && (processStep.equalsIgnoreCase ("-1") == false)) {
                    int index = processStep.indexOf('|');
                    String processStepType = processStep.substring (0, index);
                    int processStepId = Integer.parseInt (processStep.substring ((index+1), processStep.length()));

                    ArrayList lotList = EngineeringDAO.getActiveLots (-1 /*ProductID*/, processStepId, "" /*Lot Number*/);
                    request.setAttribute ("lotList", lotList);
                }
            }
            catch (ScalarException se) {
                // Exception while interaction with database
                errors.put ("Could not load Lot information", null);
                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
            }
        }


        if ("searchLots".equalsIgnoreCase (action)) {
            try {
                String lotNumber = lotShippingForm.getLotNumber();

                if ((lotNumber != null) && (lotNumber.trim().length() != 0)) {
                    ArrayList lotList = EngineeringDAO.getActiveLots (-1 /*ProductID*/, -1 /*processStepId*/, lotNumber);
                    request.setAttribute ("lotList", lotList);
                }
            }
            catch (ScalarException se) {
                // Exception while interaction with database
                errors.put ("Could not load Lot information", null);
                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
            }
        }

        if ("showLotInfoPage".equalsIgnoreCase (action)) {

            try {
                LotView lview = EngineeringDAO.getCurrentLotPosition ((String) request.getAttribute("lotId"));
                session.setAttribute (SessionKeys.LOT_VIEW, lview);
                session.setAttribute ("processStepList", loadProcessStepList (lview.getProcessStepID()));

                String returnPage = (String) request.getAttribute ("returnPage");
                session.setAttribute ("LOTVIEW_RETURN_PAGE", returnPage);

                return (mapping.findForward ("viewLotInfo"));
            }
            catch (ScalarException se) {
                // Exception while interaction with database
                errors.put ("Internal Server Error", "Could not load Lot Information");
                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
            }
        }

        if ("viewLotInfo".equalsIgnoreCase (action)) {

            try {
                String lotNumber = lotShippingForm.getLotNumberToView();
                if ((lotNumber != null) && (lotNumber.trim().length() != 0) && EngineeringDAO.isLotRunning (lotNumber)) {

                    // Load LotView object for this Lot Number
                    LotView lview = EngineeringDAO.getCurrentLotPosition (lotNumber, "Running");
                    session.setAttribute (SessionKeys.LOT_VIEW, lview);
                    session.setAttribute ("processStepList", loadProcessStepList (lview.getProcessStepID()));

                    return (mapping.findForward ("viewLotInfo"));
                }
            }
            catch (ScalarException se) {
                // Exception while interaction with database
                errors.put ("Could not load Lot Information", "Internal Server Error");
                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
            }
        }


        try {
            ArrayList marketingProductList = EngineeringDAO.getMarketingProducts();
            request.setAttribute ("marketingProductList", marketingProductList);
            retval = "success";
        }
        catch (ScalarException se) {
            // Exception while interaction with database
            errors.put ("Could not load Marketting products", "Internal Server Error");
            request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
        }


        return (mapping.findForward (retval));
    }


    private ArrayList loadProcessStepList (String processStepId) throws ScalarException {

        // Load Forward Lot Shipping Flow
        ArrayList origProcessStepList = LotShippingDAO.getForwardLotShippingFlowByProcessStepId (processStepId);
        ArrayList processStepList = new ArrayList();

        if ((origProcessStepList != null) && (origProcessStepList.size() != 0)) {

            int origProcessStepListSize = origProcessStepList.size();
            ProcessStep thisProcessStep = (ProcessStep) origProcessStepList.get (0);

            if (thisProcessStep != null) {

                String stepTypeName = thisProcessStep.getName();
                ProcessStep processStep = null;
                String name = null;

				for (int i=1; i<origProcessStepListSize; i++) {

					processStep = (ProcessStep) origProcessStepList.get (i);
					name = processStep.getName();

					if ( ("FAB".equalsIgnoreCase (stepTypeName)) && ("SORT".equalsIgnoreCase (name)) ) {
						break;
					}

					if ( ("Wafer Store".equalsIgnoreCase (stepTypeName)) && ("TEST".equalsIgnoreCase (name)) ) {
						break;
					}

					if ( ("SORT".equalsIgnoreCase (stepTypeName)) && ("TEST".equalsIgnoreCase (name)) ) {
						break;
					}

					if ( ("Die Bank".equalsIgnoreCase (stepTypeName)) && ("TEST".equalsIgnoreCase (name)) ) {
						break;
					}

					if ( ("Assembly".equalsIgnoreCase (stepTypeName)) && ("Class Store".equalsIgnoreCase (name)) ) {
						break;
					}

					if ( ("TEST".equalsIgnoreCase (stepTypeName)) && ("Finished Goods".equalsIgnoreCase (name)) ) {
						processStepList.add (processStep);
						break;
					}

                    processStepList.add (processStep);
                }
            }
        }

        return processStepList;
    }
}